<template>
    <van-popup v-model:show="isShow" position="right" @click-overlay="onClickOverlay">
        <div class="province-city-selector">
            <!-- 左侧：自定义字母索引和省份列表 -->
            <div class="province-list">
                <div class="province-container">
                    <div v-for="letter in indexList" :key="letter" class="letter-section"
                        :ref="(el) => setLetterRef(el, index)">
                        <div class="letter-header">{{ letter }}</div>
                        <div v-for="province in provincesByLetter[letter]" :key="province.code" class="province-item"
                            :class="{ active: currentProvinceCode === province.code }"
                            :id="`province.code-${province.code}`" @click="selectProvince(province, letter)">
                            {{ province.name }}
                        </div>
                    </div>
                </div>
            </div>
            <!-- 右侧：城市列表 -->
            <div class="city-content">
                <div v-if="currentCities && currentCities.length > 0" class="city-list">
                    <div v-for="city in currentCities" :key="city.code" class="city-item"
                        :class="{ active: activeCityId === city.code }" :id="`city.code-${city.code}`"
                        @click="selectCity(city)">
                        {{ city.name }}
                    </div>
                </div>
                <div v-else class="no-data">暂无城市数据</div>
            </div>
        </div>
    </van-popup>
</template>
<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useStore } from '@/pinia/index.js'
const store = useStore()
const props = defineProps({
    currentCity: Object,  //定位的城市，比如：海口
    activeCityId: String,  //城市code
    provinceData: Array,
    currentProvince: Object,
})
const currentProvince = ref(null);
const activeCityId = ref(props.activeCityId);
// 监听 props.activeCityId 的变化
watch(() => props.activeCityId, (newVal) => {
    activeCityId.value = newVal;
}, { immediate: true });
// 自定义事件 省更换  城市更换
const emit = defineEmits(['update:currentProvince', 'update:activeCityId'])
// 获取所有字母对应的 DOM 元素
//const letterRefs = useTemplateRef('letterRef');
// 使用 ref 替代 useTemplateRef
const letterRefs = ref([])
const setLetterRef = (el, index) => {
    if (el) {
        letterRefs.value[index] = el
    }
}
const isShow = computed(() => store.city_menu_show)
// 按首字母分组省份
const provincesByLetter = computed(() => {
    if (!props.provinceData || !Array.isArray(props.provinceData)) {
        return {}
    }
    const result = {};
    props.provinceData.forEach(province => {
        const letter = province.firstLetter;
        if (!result[letter]) {
            result[letter] = [];
        }
        result[letter].push(province);
    });
    return result;
});
// console.log("provincesByLetter", provincesByLetter.value)
//{firstLetter: 'A', code: '340000', name: '安徽省', cities: Array(16)}
// 索引列表（按字母顺序）
const indexList = computed(() => Object.keys(provincesByLetter.value).sort());
// 当前选中的省份code
const currentProvinceCode = computed(() => {
    return props.currentProvince ? props.currentProvince.code : null
})
// 当前城市列表
const currentCities = computed(() => {
    return props.currentProvince ? props.currentProvince.cities : []
})
// 选择省份
const selectProvince = (province, letter) => {
    emit('update:currentProvince', province)
    // 滚动到对应字母
    scrollToLetter(letter)
};
// 选择城市
const selectCity = (city) => {
    store.set_city_menu_show(false);
    store.set_current_city(city);
    emit('update:activeCityId', city.code)
};
// 滚动到指定字母
const scrollToLetter = (letter) => {
    const index = indexList.value.indexOf(letter);
    if (index >= 0 && letterRefs.value[index]) {
        letterRefs.value[index].scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
};
// 关闭弹窗
const onClickOverlay = () => {
    store.set_city_menu_show(false)
};
// 监听定位城市变化，自动匹配
watch(
    () => [props.locateCity, props.provinceData],
    ([newLocateCity, newProvinceData]) => {
        if (newLocateCity && newProvinceData && newProvinceData.length > 0) {
            matchLocatedCity()
        }
    },
    { immediate: true }
)
// 匹配定位城市
const matchLocatedCity = () => {
    if (!props.locateCity || !props.provinceData || !Array.isArray(props.provinceData)) return
    for (let province of props.provinceData) {
        const matchedCity = province.cities.find(city => {
            // 精确匹配
            if (city.name === props.locateCity) {
                return true
            }
            // 匹配"海口"与"海口市"
            if (city.name === props.locateCity + '市') {
                return true
            }
            // 匹配"海口市"与"海口"
            if (city.name.endsWith('市') && city.name.slice(0, -1) === props.locateCity) {
                return true
            }
            // 匹配特殊地区
            if (city.name.startsWith(props.locateCity) &&
                (city.name.includes('自治州') ||
                    city.name.includes('地区') ||
                    city.name.includes('盟'))) {
                return true
            }
            return false
        })
        if (matchedCity) {
            emit('update:currentProvince', province)
            emit('update:activeCityId', matchedCity.code)
            // 滚动到对应字母
            setTimeout(() => {
                scrollToLetter(province.firstLetter)
            }, 100)
            break
        }
    }
}
onMounted(() => {
    if (props.locateCity && props.provinceData && props.provinceData.length > 0) {
        matchLocatedCity()
    }
});
// 获取城市列表数据
const getCityList = async () => {
    try {
        //   const response = await fetchCityList();
        //  provinceData.value = handleCityData(response.initial);
        // [{firstLetter: 'A', code: '340000', name: '安徽省', cities: [{code: '340100', name: '合肥市'} ...]}  ...]
        //  console.log("provinceData:", provinceData.value)
        // 在获取到省份数据后，如果存在定位城市，则进行匹配
        if (props.locateCity) {
            // 遍历所有省份，查找包含定位城市的省份
            for (let province of props.provinceData) {
                const matchedCity = province.cities.find(city => {
                    // 直接匹配
                    if (city.name === props.locateCity) {
                        store.set_current_city(city);
                        return true;
                    }
                    // 匹配"XX"与"XX市"的情况，如"海口"与"海口市"
                    if (city.name === props.locateCity + '市') {
                        store.set_current_city(city);
                        return true;
                    }
                    // 匹配"XX"与"XX自治州"或"XX地区"等的情况
                    if (city.name.startsWith(props.locateCity) &&
                        (city.name.includes('自治州') ||
                            city.name.includes('地区') ||
                            city.name.includes('盟'))) {
                        store.set_current_city(city);
                        return true;
                    }
                    return false;
                });
                if (matchedCity) {
                    // 先设置当前省份
                    currentProvince.value = province;
                    // 然后直接设置活动城市的ID，避免被selectProvince中的activeCityId.value = null覆盖
                    activeCityId.value = matchedCity.code;
                    console.log('matchedCity:', matchedCity);
                    store.set_current_city(matchedCity);
                    // 滚动到对应字母
                    setTimeout(() => {
                        if (letterRefs.value) {
                            scrollToLetter(province.firstLetter);
                        }
                    }, 0);
                    break;
                }
            }
        }
    } catch (error) {
        console.error('获取城市列表失败:', error);
    }
};
</script>
<style scoped>
.province-city-selector {
    display: flex;
    height: 100vh;
    overflow: hidden;
}

/* 左侧省份列表 */
.province-list {
    width: 140px;
    background-color: #fff;
    border-right: 1px solid #ebedf0;
    overflow-y: auto;
}

.index-bar {
    padding: 10px 0;
    text-align: center;
    font-size: 12px;
    color: #999;
}

.index-item {
    padding: 5px;
    cursor: pointer;
    transition: color 0.3s;
}

.index-item:hover {
    color: #1989fa;
}

.province-container {
    padding: 10px 0;
}

.letter-section {
    margin-bottom: 10px;
}

.letter-header {
    font-size: 12px;
    color: #999;
    background-color: #f5f5f5;
    padding: 5px 10px;
    text-transform: uppercase;
}

.province-item {
    padding: 10px 10px;
    font-size: 14px;
    cursor: pointer;
    transition: background-color 0.3s;
}

.province-item.active {
    color: #1989fa;
    background-color: #f7f8fa;
}

.province-item:hover {
    background-color: #f7f8fa;
}

/* 右侧城市内容 */
.city-content {
    width: 120px;
    flex: 1;
    overflow-y: auto;
    padding: 10px;
    background-color: #f7f8fa;
}

.province-title {
    padding: 10px 0;
    font-weight: bold;
    border-bottom: 1px solid #ebedf0;
}

.city-list {
    padding: 5px 0;
}

.city-item {
    padding: 10px;
    font-size: 14px;
    cursor: pointer;
    transition: background-color 0.3s;
}

.city-item.active {
    color: #1989fa;
    background-color: #f7f8fa;
}

.city-item:hover {
    background-color: #f7f8fa;
}

.no-data {
    padding: 20px;
    text-align: center;
    color: #969799;
}
</style>